package com.tongfusoft.terminal.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.tongfusoft.base.ExtConstant;
import com.tongfusoft.base.data.ts.TsDicclass;
import com.tongfusoft.base.data.ts.TsDictionary;
import com.tongfusoft.base.data.ts.TsParameter;
import com.tongfusoft.da.help.DBUtils;
import com.tongfusoft.web.core.data.DictionaryData;
import com.tongfusoft.web.core.data.SystemParamData;
import com.tongfusoft.web.core.service.IServerInitService;

public class ServiceInitServiceImpl implements IServerInitService {

	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(ServiceInitServiceImpl.class);

	@Override
	public void initEnv(ServletContext servletContext) {
		// 加载字典表和系统参数表内容
		logger.info("server init ......");

		List<String> projects = this.getProjectIdList();

		servletContext.setAttribute(ExtConstant.DEFAULTPROJECT, this.getDefaultProjectId());

		servletContext.setAttribute(ExtConstant.SYSTEMPARAM, this.getSystemParam(projects));

		servletContext.setAttribute(ExtConstant.DICTIONARY, this.getDictionary(projects));

		logger.info("......server init");

	}

	private String getDefaultProjectId() {
		List<Map<String, String>> list = DBUtils.executeSelect("/loadData#defaultProject", new HashMap());
		if (list != null) {
			return list.get(0).get("PROJECT_ID");
		}

		return "";
	}

	private Map<String, Map<String, List<DictionaryData>>> getDictionary(List<String> projects) {
		logger.info("load Dictionary Data......");
		Map<String, Map<String, List<DictionaryData>>> dictionaryMap = new HashMap<String, Map<String, List<DictionaryData>>>();

		try {
			List<TsDicclass> dictClass = DBUtils.executeSelect("/loadData#dictionaryClass", new HashMap());

			// 填充默认Project
			for (String project : projects) {
				Map<String, List<DictionaryData>> dictList = new HashMap<String, List<DictionaryData>>();

				for (TsDicclass dict : dictClass) {
					if (StringUtils.equals(dict.getProjectId(), "0")
							|| StringUtils.equals(dict.getProjectId(), project)) {
						dictList.put(dict.getName(), new ArrayList<DictionaryData>());
					}
				}

				dictionaryMap.put(project, dictList);
			}

			// 填充dictionary
			List<Map<String, Object>> dictionarys = DBUtils.executeSelect("/loadData#dictionary", new HashMap());
			for (Map<String, Object> map : dictionarys) {
				TsDictionary dict = new TsDictionary();
				dict.setDictkeyName((String) map.get("DICTKEY_NAME"));
				dict.setDictkeyValue((String) map.get("DICTKEY_VALUE"));
				dict.setDictclassId((String) map.get("DICTCLASS_NAME"));
				// dict.setShowOrder(Integer.parseInt(map.get("SHOW_ORDER").toString()));

				if (StringUtils.equals((String) map.get("PROJECT_ID"), "0")) {
					Iterator<Entry<String, Map<String, List<DictionaryData>>>> iter = dictionaryMap.entrySet()
							.iterator();
					while (iter.hasNext()) {
						iter.next().getValue().get(map.get("DICTCLASS_NAME")).add(dict);
					}
				} else {
					dictionaryMap.get(map.get("PROJECT_ID")).get(map.get("DICTCLASS_NAME")).add(dict);
				}
			}

		} catch (Exception e) {
			logger.error("load Dictionary Data error:" + e.getMessage());
		}

		return dictionaryMap;
	}

	private Map<String, Map<String, SystemParamData>> getSystemParam(List<String> projects) {
		logger.info("load System Data......");

		Map<String, Map<String, SystemParamData>> paramMap = new HashMap<String, Map<String, SystemParamData>>();

		try {
			List<TsParameter> paramList = DBUtils.executeSelect("/loadData#systemparam", new HashMap());

			// 默认填充
			for (String project : projects) {
				paramMap.put(project, new HashMap<String, SystemParamData>());
			}

			// 填充数据
			for (TsParameter param : paramList) {
				if (param.getProjectId().equals("0")) { // 通用参数
					Iterator<Entry<String, Map<String, SystemParamData>>> iter = paramMap.entrySet().iterator();
					while (iter.hasNext()) {
						iter.next().getValue().put(param.getParamCode(), param);
					}
				} else {
					paramMap.get(param.getProjectId()).put(param.getParamCode(), param);
				}

			}

		} catch (Exception e) {
			logger.error("load System Param error:" + e.getMessage());
		}

		return paramMap;
	}

	private List<String> getProjectIdList() {
		try {
			List<Map<String, Object>> projects = DBUtils.executeSelect("/loadData#project", new HashMap());
			List<String> projectList = new ArrayList<String>();

			for (Map<String, Object> project : projects) {
				projectList.add((String) project.get("PROJECT_ID"));
			}

			return projectList;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return Collections.EMPTY_LIST;
		}
	}

}
